package com.yuan.service.subscribe.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.yuan.common.date.DateUtil;
import com.yuan.common.mail.SendMail;
import com.yuan.dao.goods.GoodsDao;
import com.yuan.dao.subscribe.SubscribeDao;
import com.yuan.goods.Goods;
import com.yuan.service.subscribe.SubscribeService;
import com.yuan.subscribe.Subscribe;

public class SubscribeServiceImpl implements SubscribeService {

	private SubscribeDao subscribeDao;

	private GoodsDao goodsDao;

	private SendMail sendMail;

	public void save(Subscribe subscribe) throws SQLException {
		subscribeDao.save(subscribe);
	}

	public List<Subscribe> readEffect() throws SQLException {
		return subscribeDao.readEffect();
	}

	public void sendMail() throws Exception {
		// 读取订阅者的邮件地址
		List<Subscribe> subscribes = this.readEffect();

		if (subscribes == null || subscribes.isEmpty()) {
			return;
		}

		List<Goods> goodses = goodsDao.readToday(null);

		if(goodses==null || goodses.isEmpty()){
			return;
		}
		
		int subscribeSize=goodses.size();
		
		if(subscribeSize>10){
			subscribeSize=10;
		}
		String content = content(goodses.subList(0, subscribeSize));
		
		for (Subscribe subscribe : subscribes) {
			sendMail.sendEmail(subscribe.getEmail(),
					"爱0元：【订阅邮件】" + DateUtil.getPresentDateFormat_yyyyMMdd(),
					content);

			// 休眠1min
			Thread.sleep(60000);
		}

	}

	public String content(List<Goods> goodses) throws Exception {
		VelocityEngine velocity = new VelocityEngine();
		HashMap model = new HashMap();
		model.put("goodses", goodses);

		Properties prop = new Properties();
		prop.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
		prop.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
		prop.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
		prop.put("file.resource.loader.class",
				"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		velocity.init(prop);

		String str = VelocityEngineUtils.mergeTemplateIntoString(velocity,
				"subscribe.vm", model);

		return str;
	}

	public SubscribeDao getSubscribeDao() {
		return subscribeDao;
	}

	public void setSubscribeDao(SubscribeDao subscribeDao) {
		this.subscribeDao = subscribeDao;
	}

	public SendMail getSendMail() {
		return sendMail;
	}

	public void setSendMail(SendMail sendMail) {
		this.sendMail = sendMail;
	}

	public GoodsDao getGoodsDao() {
		return goodsDao;
	}

	public void setGoodsDao(GoodsDao goodsDao) {
		this.goodsDao = goodsDao;
	}

}
